/*******************************************************************************
* FileName:         LinkStack.cpp
* Author:           李智铭
* Student Number:   3022206093
* Date:             2024/10/23 15：25：00
* Version:          v1.0
* Description:      Data Structure Experiment #3
*******************************************************************************/


#include "LinkStack.h"
#include <iostream>
#include <stdexcept>

LinkStack::LinkStack(){
    head = nullptr;     //初始化头指针为空
    length = 0;
}

LinkStack::~LinkStack(){
    while(head != nullptr){     //迭代弹出各栈节点
        pop();
    }
}

void LinkStack::push_back(int data){
    StackNode* newnode = new StackNode;     //初始化一个新的栈节点
    newnode -> value = data;
    newnode -> next = head;     //采用头插法插入新的栈节点
    head = newnode;    
    length++;     //栈长+1
}

int LinkStack::top() const{
    if(head == nullptr){     //判断栈空
        throw std :: underflow_error("STACK EMPTY");
    }
    return head -> value;
}

void LinkStack::pop(){
    if(head == nullptr){     //判断栈空
        throw std :: underflow_error("STACK EMPTY");
    }
    StackNode* temp = new StackNode;     //用临时节点存放当前头节点
    temp = head;
    head = head -> next;     //弹出当前头节点
    delete temp;      //删除旧头节点，防止内存泄漏
    length--;;     //栈长-1
}